package biznussoft.metercor.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import biznussoft.metercor.utils.Session;

public class MyServiceClass  extends IntentService{

	private HttpURLConnection mHttpUrlConnection;
	private URL mUrl;
	public MyServiceClass() {
		super("MyService");
	}

	@Override              
	protected void onHandleIntent(Intent intent) {
		try{
		mUrl = new URL(intent.getStringExtra("URL"));
		mHttpUrlConnection = (HttpURLConnection) mUrl.openConnection();
		mHttpUrlConnection.setRequestMethod("POST");
		mHttpUrlConnection.setRequestProperty("Content-type", "application/json");
		mHttpUrlConnection.setRequestProperty("Authorization", "OAuth "+ Session.sAccesToken);
		Log.i("RGT","Acess token is  :"+Session.sAccesToken);
		                    
		String response  = convertToString(mHttpUrlConnection.getInputStream());
		Intent i = new Intent("RESPONSE").putExtra("Response",response);
		sendBroadcast(i);
		}catch(Exception ex){
			Log.i("RGT","Excption is  :"+ex.getMessage());
		}
		
	}

	private String convertToString(InputStream stream){
	
			BufferedReader  bReader = null;
			bReader = new BufferedReader(new InputStreamReader(stream));
			StringBuilder sb = new StringBuilder();
			String line = null;
			try {
				while ((line = bReader.readLine()) != null) {

					sb.append(line + "\n");
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {                 
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return sb.toString();
			
		
	}
}
